Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

207
Visualizações
How to Handle multiple checkbox with default value checked using state with some array of object [React-JS Typescript]

i'm using multiple input checkbox for my form input in react. like image bellow:

enter image description here

this is some part of my code:

interface CheckType {
  id: any;
  desc: string;
  checked: boolean;
}

interface CheckListInputProps {
  options: Array<CheckType>;
  onChange: (e: React.ChangeEvent<HTMLInputElement>, data: Array<CheckType>) => void
}

const CheckListInput: React.FC<CheckListInputProps> = ({options, onChange}) => {
  const [initOpt, setInitOpt] = useState<Array<CheckType>([])

  useEffect(()=>{
    setInitOpt(options);
  },[options])

const changeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
  let {value, checked} = e.currentTarget
  let index = initOpt.findIndex(item => item.id===value);
  initOpt[index].checked = checked
  setInitOpt(initOpt)
  onChange(e, initOpt);
}

  return (
    <div>
      {
        initOpt.map((item, index) => (
          <div key={index}>
            <input value={item.id} checked={item.checked} onChange={changeHandler}/>
            <label>{item.desc}</label>
          </div>
       )}
    </div>)
}

when i called this function in other file:

const ChangeHandler = (e: React.ChangeEvent<HTMLInputElement>, data: Array<any>) => {
  console.log(data);
}

const options = [
  {id: 0, desc: "GET", checked: false},
  {id: 1, desc: "POST", checked: false},
  {id: 2, desc: "DELETE", checked: false}
]

return <CheckListInput options={options} onChange={ChangeHandler}/

everything works fine. the log show what i want. but the problem is in interface the checkbox won't change into checked or unchecked. how do i fix this? is it any wrong with this checked={item.checked}

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda